/**
 * Created by liwei on 17/5/25.
 */

'use strict'
import Vue from 'vue'

var exportTemplete = require('html!./updata.html');
require('../../../js/jqueryUi/jquery-ui.min.less');
require('../../../js/webupload/webuploader.less');
require('./data.less');

module.exports = {
    template: exportTemplete,
    data:function(){
        return {
            dataList:[],
            fileHead:[],
            fileList:[],
            userId:localStorage.getItem("userId"),
            modelId:'',
            modelName:'',
            modelDesc:'',
            modelPic:''
        }
    },
    created:function(){
        this.modelId = this.$route.query.modelId;
        // this.modelPic = this.$route.query.modelPic;
        this.modelName = this.$route.query.modelName;
        this.modelDesc = this.$route.query.modelDesc;
        this.getAllData();
    },
    mounted:function(){
        this.file();
    },
    updated:function(){
        this.droppable();
        //this.del();
        //this.relaterClick();
    },
    methods:{
      rtnModelList:function () {
        var me = this;
        me.$router.push({ path: '/product/model-list'});
      },
        getAllData:function(){
           var me = this;
            me.$http.get('/eyeModelController/getModelFieldById.do?modelId='+me.modelId)
            .then(function(res) {
                    me.dataList = [];
                if(res.data.code == '000000'){

                    me.dataList = res.data.result.dataList;
                }else{
                    layer.msg('系统繁忙，请稍后再试');
                }

            }.bind(this));
        },
        /**
         * 获取浏览器url参数
         * @param  {String} name 参数值
         *
         */
        getQueryString:function(name){
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        },
        /**
         * 文件上传
         */
        file:function(){

            var _this = this;

            var uploader = WebUploader.create({
                // swf文件路径
                swf:'http://cdn.staticfile.org/webuploader/0.1.0/Uploader.swf',
                // 文件接收服务端。
                server: Vue.prototype.$http.defaults.baseURL+'/fileUploadController/upload.do',
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                auto: true,
                formData:{
                    modelId:_this.modelId,
                    userId: _this.userId
                },
                pick: '#picker',
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
              fileNumLimit:10,//验证文件总数量, 超出则不允许加入队列
              fileSingleSizeLimit:10*1024*1024,//验证单个文件大小是否超出限制, 超出则不允许加入队列。
              //fileSizeLimit:100*1024*1024,//验证文件总大小是否超出限制, 超出则不允许加入队列
                resize: false,
                duplicate:true,
                accept:{
                    title: 'Applications',
                    extensions: 'xlsx,xls,csv',
                    mimeTypes: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'
                }
            });


            // 当有文件被添加进队列的时候
            uploader.on( 'fileQueued', function( file ) {
                $('#thelist').html( '<div id="' + file.id + '" class="item">'+
                  '<h4 class="info">' + file.name + '</h4>' +
                  '<p class="state">等待上传...</p>' +
                  '</div>');
            });


            // 文件上传过程中创建进度条实时显示。
            uploader.on( 'uploadProgress', function( file, percentage ) {
                var $li = $( '#'+file.id ),
                    $percent = $li.find('.progress .progress-bar');

                // 避免重复创建
                if ( !$percent.length ) {
                    $percent = $('<div class="progress progress-striped active">' +
                        '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                        '</div>' +
                        '</div>').appendTo( $li ).find('.progress-bar');
                }

                $li.find('p.state').text('上传中...');

                $percent.css( 'width', percentage * 100 + '%' );

            });

            uploader.on( 'uploadSuccess', function( file,response) {
                $( '#'+file.id ).find('p.state').text('已上传');

                if(response.code == '000000'){
                    var _fileList = [];
                    _this.fileHead.push(response.result[1]);
                    for(var i = 0;i<response.result[0].length;i++){
                        _fileList.push(response.result[0][i]);
                    }
                    _this.fileList.push(_fileList);
                    uploader.removeFile(file,true);
                }else{
                    layer.msg('数据格式错误！请重新上传！');
                }

            });

            uploader.on( 'uploadError', function( file ) {
                $( '#'+file.id ).find('p.state').text('上传出错');
            });

            uploader.on( 'uploadComplete', function( file ) {
                $( '#'+file.id ).find('.progress').fadeOut();
            });
            // 所有文件上传成功后调用
            uploader.on('uploadFinished', function () {
              //清空队列
              uploader.reset();
            });


        },
        /**
         * 删除数据源
         * @param $
         */
        del:function(e,className){
            var _this = this;
            var me =$(e.currentTarget);
            var arry = [];
            var deleteLay = layer.confirm('涉及对应数据字段将一并删除，是否确认删除？', {
                btn: ['是', '否'] //按钮
              }, function () {
              _this.$http.post('/fileUploadController/upload/deleteTableByName.do?className=' + className)
                .then(function (res) {
                  if (res.data.code == '000000') {
                    layer.msg('删除成功！');
                    me.closest('dl').find('span').each(function(){
                      arry.push($(this).text());
                    });
                    $('.droppable').find('.actual-data').each(function(){
                      if($.inArray($(this).text(),arry)!=-1){
                        $(this).closest('.droppable-data').hide().prev().show();
                      }
                    });
                    me.closest('dl').siblings('dl').find('span').removeClass('col_red');
                    me.closest('dl').remove();
                  } else {
                    layer.msg('系统繁忙，请稍后再试');
                  }
                }.bind(_this));
            });
        },
        /**
         * 拖拽效果
         * @param $
         */
        droppable:function(){

            var sourceData;

            $('.table-main').find('span').draggable({
                helper: function( event ) {
                    return $( '<div class="clone-span">'+$(this).text()+'</div>');
                },
                start:function(){
                    sourceData = $(this);
                    $('.placeholder').addClass('onplaceholder');
                },
                stop: function( event, ui ) {
                    $('.placeholder').removeClass('onplaceholder');
                    sourceData = null;
                }
            });

            $('.droppable').droppable({
                drop: function( event, ui ) {
                    $(this).find('.actual-data').html($(sourceData).html()).data({
                        'tname':$(sourceData).data('tname'),
                        'cname':$(sourceData).data('cname')
                    }).closest('.droppable').find('.placeholder').hide().end().find('.droppable-data').show();
                }
            });

            $('.droppable-data').find('button').on('click',function(){
                layer.msg('删除成功！');
                $(this).closest('.droppable-data').hide().prev().show();
            });
        },

        /**
         * 确定关联关系
         */
        relaterClick:function(){

            $('.table-main').find('span').on('click',function(){
               var _span = $(this), istrue = false;
               $(this).closest('dl').next('dl').find('span').each(function(){
                   if($(this).text() == _span.text()){

                       $(this).closest('dl').find('em').text($(this).text()).data({
                           'tableFirstName':_span.data('tname'),
                           'tableLastName':$(this).data('tname'),
                           'colFirstName':_span.data('cname'),
                           'colLastName':$(this).data('cname')
                       });

                        istrue = true;
                        return;
                   }
               });

              if(!istrue){
                  layer.msg('您选择的关联字段不一致，请重新选择或修改元数据对应字段名称！');
              }


            })
        },
        /**
         * 下一步
         */
        submit:function(){
            var layLoad = layer.load(2, {shade: 0.1, area: ['32px', '64px']});
            var me = this;
            var arr = '',isSubmit = false, relate = [],_relate = [];
            $('#modeData').find('tr').each(function(){
                var _this = $(this).find('.actual-data');
                if(_this.text() == ''){
                    isSubmit = false;
                    return;
                }
                arr+=$(this).find('em').text()+'='+_this.data('cname')+'='+_this.data('tname')+',';
                isSubmit = true;
            });

            // $('.table-main').find('em.col_red').each(function(){
            //     var _this = $(this);
            //     if(_this.text() !=''){
            //         relate.push({
            //             'tableFirstName':_this.data('tableFirstName'),
            //             'tableLastName':_this.data('tableLastName'),
            //             'colFirstName':_this.data('colFirstName'),
            //             'colLastName':_this.data('colLastName')
            //         });
            //     }
            //
            // });


            // if($('.table-main').find('dl:last').find('em.col_red').text() == '' && $('.table-main').find('dl').size() > 1){
            //     layer.msg('请点击匹配表之间关联关系！');
            //     isSubmit = false;
            //     layer.close(layLoad);
            //     return;
            // }

            if(isSubmit){
                isSubmit = false;

                $.ajax({
                    url:Vue.prototype.$http.defaults.baseURL+"/eyeModelController/insertDataByModelid.do",
                    method:"post",
                    data:{
                        'eye_model_id':me.modelId,
                        'Inviolate':arr,
                        // 'Relate':JSON.stringify(relate)
                    },
                    dataType:"json",
                    success:function(res){
                        layer.close(layLoad);
                        if(res.code == '000000'){
                            layer.msg('发送成功');
                            localStorage.setItem('modelPic',me.modelPic);
                            localStorage.setItem('modelId',me.modelId);
                            localStorage.setItem('modelName',me.modelName);
                            //me.$router.push('/product/modelUseDataExplore');
                            me.$router.push({ path: '/product/modelUseDataExplore', query: { modelId: me.modelId+"",modelName:me.modelName,modelDesc:me.modelDesc }});
                        }else{
                            layer.msg("系统繁忙，请稍后重试");
                        }
                        isSubmit = true;
                    },
                    error:function(error){
                        console.error(error,"error");
                    }
                })
            }else{
                layer.close(layLoad);
                layer.msg('请拖入全部关联字段');
            }

        }
    }
}
